//==================客户端======================
const dateKit = require( "./util/dateKit");
const dataKit = require( "./util/dataKit");
const util = require( "./util/util")
const clientService = require( "./util/clientService")

/**
 * 登录
 * userNick 用户昵称
 */
exports.login = async (context) => {
    const {userNick} = context.data;
    const {openId,appOwnerOpenId} = context;

    if(!userNick){
        return {code:-1,msg:"userNick是必须的"};
    }
    
    let userInfo = await clientService.getUserByOpenId(context,openId);
    if(!userInfo){
        //首次登陆
        userInfo = {openId:openId,
                    createTime:dateKit.getCurrentDateTime(),
                    //初始化字段数据
                    drawNum:0,
                    gameNum:1,
                    eliminateNum:1,
                    bombNum:1,
                    addStepNum:1,
                    integral:0,
                    isFirstLogin:true,
                    version:0,
                  };
    }else{
      //第二次登录
      userInfo.isFirstLogin=false;
    }
    
    userInfo.appOwnerOpenId=appOwnerOpenId;
    userInfo.userNick=userNick;
    userInfo.loginTime = dateKit.getCurrentDateTime();
    const result = await dataKit.insertOrUpdate(context,"user_info",userInfo);
    //增加登录日志
    await dataKit.insertOne(context,"user_data",{type:"login",remark:"用户登录",openId,userNick,createTime:dateKit.getCurrentDateTime()})
    return {code:0,msg:"登录成功",data:result};
};

/**
 * 获取当前用户信息
 */
exports.getUserInfo = async (context) => {
  const {openId} = context;
  let userInfo = await clientService.getUserByOpenId(context,openId);
  return {code:0,msg:"获取成功",data:userInfo};
}
